package cn.yunhe.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.yunhe.dao.DaoFactory;
import cn.yunhe.dao.ICateDao;
import cn.yunhe.entity.Cate;

public class CateDaoImpl implements ICateDao {
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	public boolean addCate(Cate cate) {
		boolean flag = false;
		try {
			conn = DaoFactory.getConn();
			String sql = "insert into tb_cate values(seq_cateid.nextval,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, cate.getCateName());
			int result = pstmt.executeUpdate();
			if (result > 0) {
				flag = true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoFactory.closeAll(conn, pstmt, null);
		}

		return flag;
	}

	public List<Cate> getAllCate() {
		List<Cate> cates = new ArrayList<Cate>();
		try {
			conn = DaoFactory.getConn();
			String sql = "select * from tb_cate";
			pstmt = conn.prepareStatement(sql);

			rs = pstmt.executeQuery();

			while (rs.next()) {
				Cate c = new Cate(rs.getInt("cate_id"),
						rs.getString("cate_name"));
				cates.add(c);

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoFactory.closeAll(conn, pstmt, rs);
		}

		return cates;
	}

	public boolean deleteCateById(int cateId) {
		boolean flag = false;

		try {
			conn = DaoFactory.getConn();
			String sql = "delete from tb_cate where cate_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, cateId);

			int result = pstmt.executeUpdate();

			if (result > 0) {
				flag = true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoFactory.closeAll(conn, pstmt, rs);
		}

		return flag;
	}

	public Cate getCateById(int cateId) {
		Cate cate = null;
		try {
			conn = DaoFactory.getConn();
			String sql = "select * from tb_cate where cate_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, cateId);
			rs = pstmt.executeQuery();

			if (rs.next()) {
				cate = new Cate(rs.getInt("cate_id"), rs.getString("cate_name"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoFactory.closeAll(conn, pstmt, rs);
		}

		return cate;
	}

	public boolean updateCate(Cate cate) {
		boolean flag = false;
		try {
			conn = DaoFactory.getConn();
			String sql = "update tb_cate set cate_name = ? where cate_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, cate.getCateName());
			pstmt.setInt(2, cate.getCateId());

			int result = pstmt.executeUpdate();
			if (result > 0) {
				flag = true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoFactory.closeAll(conn, pstmt, rs);
		}

		return flag;
	}

}
